package org.example.Thread02;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

public class Dome_Thread02 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //实现Callable接口，定义任务
        Callable<Integer> callable=new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                System.out.println("执行运算...");
                int sum=0;
                //执行累加操作
                for(int i=1;i<=1000;i++){
                    sum+=i;
                }
                //休眠三秒，模拟业务处理的时间
                TimeUnit.SECONDS.sleep(3);
                System.out.println("执行运算完成...");
                return sum;
            }
        };
        //Callable要配合FutureTask一起使用，FutureTask用来获取Callable的执行结果
        FutureTask<Integer> futureTask=new FutureTask<>(callable);
        //FutureTask当做构造参数传入到Thread构造方法中
        Thread t1=new Thread(futureTask);
        //启动线程
        t1.start();
        Integer result=futureTask.get();
        System.out.println("执行结果是："+result);
    }
}
